package com.spring.proxy;

import com.spring.service.AccountService;
import com.spring.utils.TransactionManagement;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 *
 * 用于创建代理对象的工厂
 */
public class ProxyBeanFactory {

    private AccountService accountService;
    private  TransactionManagement txManagement;

    /**
     * 生成accountService的代理对象
     */
   public AccountService getAccountService(){
     return  (AccountService)Proxy.newProxyInstance(
             accountService.getClass().getClassLoader(),
                accountService.getClass().getInterfaces(),
                new InvocationHandler() {
                    /**
                     * 添加事务的支持
                     * @param proxy
                     * @param method
                     * @param args
                     * @return
                     * @throws Throwable
                     */
                    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {

                        Object returnValue = null;

                        try {
                            txManagement.beginTransaction();
                            returnValue = method.invoke(accountService, args);
                            txManagement.commit();
                            return returnValue;
                        } catch (Exception e) {
                            txManagement.rollback();
                            throw new RuntimeException(e);
                        } finally {
                            txManagement.release();
                        }
                    }
                });
    }

    public void setAccountService(AccountService accountService) {
        this.accountService = accountService;
    }

    public TransactionManagement getTxManagement() {
        return txManagement;
    }

    public void setTxManagement(TransactionManagement txManagement) {
        this.txManagement = txManagement;
    }
}
